package com.likou.second_challenge;

public class q23 {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) {
            return null;
        }
        while (lists.length >= 2) {
            ListNode[] tempLists = new ListNode[lists.length % 2 == 0 ? lists.length / 2 : lists.length / 2 + 1];
            int index = 0;
            for (int i = 0; i < lists.length; i += 2) {
                ListNode p1 = lists[i];
                ListNode p2 = null;
                if (i + 1 < lists.length) {
                    p2 = lists[i + 1];
                }
                ListNode merageTowList = merageTowList(p1, p2);
                tempLists[index] = merageTowList;
                index++;
            }

            lists = tempLists;
        }

        return lists[0];
    }

    private ListNode merageTowList(ListNode list1, ListNode list2) {
        ListNode ans = new ListNode(0);
        ListNode p = ans;
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                p.next = new ListNode(list1.val);
                list1 = list1.next;
            } else {
                p.next = new ListNode(list2.val);
                list2 = list2.next;
            }
            p = p.next;
        }

        if (list1 != null) {
            p.next = list1;
        } else {
            p.next = list2;
        }

        return ans.next;
    }
}
